package org.example.trainTicketSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.trainTicketSystem.DTO.LoginDTO;
import org.example.trainTicketSystem.DTO.RegisterDTO;
import org.example.trainTicketSystem.entity.User;
import org.example.trainTicketSystem.service.UserService;
import org.example.trainTicketSystem.utils.JwtUtil;
import org.example.trainTicketSystem.utils.ResponseResult;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;
    private final PasswordEncoder passwordEncoder;

    @PostMapping("/register")
    public ResponseResult<User> register(@Valid @RequestBody RegisterDTO registerDTO) {
        // 检查用户是否已存在
        if (userService.selectUserByUsername(registerDTO.getUsername()) != null) {
            return ResponseResult.fail("用户名已存在");
        }

        // 密码加密
        User user = new User(registerDTO);
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));

        // 日志记录
        log.info("User registration attempt: {}", registerDTO.getUsername());

        if (userService.save(user)) {
            log.info("User registered successfully: {}", user.getUsername());
            return ResponseResult.success("用户注册成功", user);
        } else {
            log.error("User registration failed: {}", registerDTO.getUsername());
            return ResponseResult.fail("用户注册失败");
        }
    }

    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        log.info("User login attempt: {}", loginDTO.getUsername());

        User user = userService.selectUserByUsername(loginDTO.getUsername());
        if (user == null || !passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            log.warn("Login failed for username: {}", loginDTO.getUsername());
            return ResponseResult.fail("账号或密码错误");
        }

        String token = jwtUtil.generateToken(user);
        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("token", token);

        log.info("User logged in successfully: {}", loginDTO.getUsername());
        return ResponseResult.success("登录成功", result);
    }

    @GetMapping
    public ResponseResult<User> getUserById(@RequestParam int userId) {
        User user = userService.getById(userId);
        if (user == null) {
            log.warn("User not found with ID: {}", userId);
            return ResponseResult.fail("不存在该用户");
        }
        return ResponseResult.success("用户信息查询成功", user);
    }

    @GetMapping("/all")
    public ResponseResult<Page<User>> getAllUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {

        Boolean isAdmin = (Boolean) request.getAttribute("isAdmin");

        if (!Boolean.TRUE.equals(isAdmin)) {
            log.warn("Unauthorized access to user list");
            return ResponseResult.fail("权限不足");
        }

        // 规范化分页参数
        page = Math.max(1, page);
        size = Math.min(Math.max(1, size), 100);

        Page<User> users = userService.selectAllUser(page, size);
        if (users == null || users.getRecords().isEmpty()) {
            log.info("No users found");
            return ResponseResult.fail("目前暂无用户");
        }
        return ResponseResult.success("用户获取成功", users);
    }

    @DeleteMapping()
    public ResponseResult<User> deleteUserById(
            @RequestParam int userId,
            HttpServletRequest request) {

        Boolean isAdmin = (Boolean) request.getAttribute("isAdmin");

        if (!Boolean.TRUE.equals(isAdmin)) {
            log.warn("Unauthorized deletion attempt for user ID: {}", userId);
            return ResponseResult.fail("权限不足");
        }

        User user = userService.getById(userId);
        if (user == null) {
            log.warn("Attempted to delete non-existent user ID: {}", userId);
            return ResponseResult.fail("暂无此用户");
        }

        if (Boolean.TRUE.equals(user.getAdmin())) {
            log.warn("Attempted to delete an admin user ID: {}", userId);
            return ResponseResult.fail("你不能删除管理用户");
        }

        if (userService.removeById(userId)) {
            log.info("User deleted successfully: {}", userId);
            return ResponseResult.success("删除该用户成功", user);
        } else {
            log.error("Failed to delete user: {}", userId);
            return ResponseResult.fail("删除该用户失败");
        }
    }

    @PutMapping()
    public ResponseResult<Map<String, Object>> updateUserById(@Valid @RequestBody User user) {
        // 更新前对密码进行加密
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        if (userService.updateById(user)) {
            String token = jwtUtil.generateToken(user);
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            result.put("token", token);

            log.info("User updated successfully: {}", user.getUserId());
            return ResponseResult.success("用户信息更新成功", result);
        } else {
            log.error("Failed to update user: {}", user.getUserId());
            return ResponseResult.fail("用户信息更新失败");
        }
    }
}